package com.le.tester.tip;

//import jodd.datetime.TimeUtil;
//import org.openjdk.jmh.runner.RunnerException;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * createTime：2022/2/11 16:18
 * description：reentrantLock基本用法
 */
public class ReentrantLockTester {
    //这边的new reentrantLock默认的是使用不公平锁（不管线程排队的时间，直接抢锁随机）
    //而reentrantLock公平锁，条件是谁等待的时间最长，那么就获取到锁
    private static final Lock LOCK = new ReentrantLock();

    public static void main(String[] args) {
//        new Thread(test(), "线程A").start();
//        new Thread(test(), "线程B").start();
//        new Thread() {
//            @Override
//            public void run() {
//                test();
//            }
//        }.start();
        new Thread(ReentrantLockTester::test, "线程A").start();
        new Thread(ReentrantLockTester::test, "线程B").start();
    }


    //类中的静态方法，可以使用A::f
    public static void test() {
        LOCK.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "获取到了锁！");
            TimeUnit.SECONDS.sleep(2);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            System.out.println(Thread.currentThread().getName() + "释放了锁！");
            LOCK.unlock();
        }
    }

}
